package com.hengpeng.itfin.service.impl;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.exception.ServiceResultFactory;
import com.hengpeng.itfin.common.SystemConfigUtil;
import com.hengpeng.itfin.exception.TransException;
import com.hengpeng.itfin.service.DrawingService;
import com.hengpeng.itfinbase.constants.RespCodeConstants;
import com.hengpeng.itfinbase.message.ResponseMessage;
import com.hengpeng.itfinbase.message.partner.CashRequestMsg;
import com.hengpeng.itfinbase.persist.AccountLog;
import com.hengpeng.itfinbase.persist.Drawing;
import com.hengpeng.itfinbase.persist.Drawing.DrawingState;
import com.hengpeng.itfinbase.persist.Payment;
import com.hengpeng.itfinbase.persist.Payment.PayStatus;
import com.hengpeng.itfinbase.persist.UserBankCard;
import com.hengpeng.itfinbase.persist.UserInfo;

/**
 * <pre>
 * 提现服务
 * </pre>
 * @author shanguogang
 * @version 1.0, 2015-8-12
 */
@Transactional
@Service
@Lazy
public class DrawingServiceImpl extends BaseServiceImpl implements DrawingService, ApplicationContextAware
{
	private ApplicationContext context;

	/**
	 * <pre>
	 * 用户提现请求
	 * </pre>
	 * @param request
	 * @param isCheckPassword
	 * @return
	 */
	@Override
	public ResponseMessage drawRequest(CashRequestMsg request)
	{
		ResponseMessage response = new ResponseMessage();
		UserInfo userinfo = daoFactory.getUserInfoDao().get(request.getUserId());
		UserBankCard bankCard = serviceFactory.getPersistService().get(UserBankCard.class, request.getBankCardId());
		Payment payment = serviceFactory.getPaymentService().findByOrderId(request.getOrdId());
		if (payment.getStatus() != PayStatus.PAYING)
		{
			throw new TransException("提现过程中！");
		}
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date(System.currentTimeMillis() + 2 * 24 * 60 * 60 * 1000));
		String planDate = "预计"
				+ (calendar.get(Calendar.MONTH) + 1 < 10 ? "0" + (calendar.get(Calendar.MONTH) + 1) : calendar
						.get(Calendar.MONTH) + 1)
				+ "月"
				+ (calendar.get(Calendar.DAY_OF_MONTH) < 10 ? "0" + calendar.get(Calendar.DAY_OF_MONTH) : calendar
						.get(Calendar.DAY_OF_MONTH)) + "日24点前到账";
		// 插入提现记录
		Drawing drawing = new Drawing();
		drawing.setUserId(userinfo.getId());
		drawing.setUserName(userinfo.getUserName());
		drawing.setOrdId(request.getOrdId());
		drawing.setProviderId(request.getProviderId());
		drawing.setCardNumber(userinfo.getCardNumber());
		drawing.setRealName(bankCard.getRealName());
		drawing.setPlanDate(planDate);// 预计到账时间
		drawing.setBankName(bankCard.getBankName().getText());
		drawing.setBankCardNo(bankCard.getBankCardNo());
		drawing.setBranch(bankCard.getBranch());
		drawing.setCity(bankCard.getCity());
		drawing.setProvince(bankCard.getProvince());
		drawing.setSubbranch(bankCard.getSubbranch());
		drawing.setMoney(payment.getMoney());
		drawing.setRequestTime(new Date());
		String configValue = SystemConfigUtil.getConfigValue("DRAWING_WAITCONFIRM_LIMITED_CENT");
		if (configValue == null)
		{
			drawing.setState(DrawingState.WAIT);
		}
		else
		{
			if (Integer.parseInt(configValue) >= drawing.getMoney())
			{
				drawing.setState(DrawingState.WAIT);
			}
			else
			{
				drawing.setState(DrawingState.WAITCONFIRM);
			}
		}
		drawing = serviceFactory.getPersistService().save(drawing);
		response.setRespDesc(planDate);
		return response;
	}

	@Override
	public ServiceResult<Boolean> dealResult(String providerId, String ordId, DrawingState state, String msg)
	{
		Drawing drawing = serviceFactory
				.getDaoFactory()
				.getCommonDao()
				.getEntityByNamedQuery(Drawing.class, "drawing.queryByProviderIdAndOrdId",
						new Object[] { providerId, ordId });
		drawing = serviceFactory.getDaoFactory().getCommonDao().lockObject(Drawing.class, drawing.getId());
		if (drawing.getState() == DrawingState.DEALING)
		{// 状态正确
			Payment payment = serviceFactory.getPaymentService().findByOrderId(ordId);
			payment = daoFactory.getCommonDao().lockObject(Payment.class, payment.getId());
			if (state == DrawingState.SUCCESS)
			{// 提款成功
				drawing.setState(DrawingState.SUCCESS);
				drawing.setLastTime(new Date());
				drawing.setFailedMsg(msg);
				serviceFactory.getPersistService().update(drawing);

				payment.setStatus(PayStatus.SUCCESS);
				payment.setOverTime(new Date());
				payment.setUpdateTime(new Date());
				payment.setChargeMoney(drawing.getChargeMoney());
				serviceFactory.getAccountService().unfreezeForSuc(payment.getUserId(), AccountLog.TransType.DRAW,
						Long.parseLong(String.valueOf(payment.getMoney())), String.valueOf(payment.getId()), "提现成功");
				return ServiceResultFactory.getServiceResult(RespCodeConstants.CommonCode.TRANS_SUC, true);
			}
			else if (state == DrawingState.FAILED)
			{// 提款失败

				drawing.setState(DrawingState.REFUNDED);
				drawing.setLastTime(new Date());
				drawing.setFailedMsg(msg);
				serviceFactory.getPersistService().update(drawing);

				payment.setStatus(PayStatus.FAILED);
				payment.setOverTime(new Date());
				payment.setUpdateTime(new Date());
				serviceFactory.getAccountService().unfreezeForFail(payment.getUserId(), AccountLog.TransType.DRAW,
						Long.parseLong(String.valueOf(payment.getMoney())), String.valueOf(payment.getId()), "提现失败解冻");
				return ServiceResultFactory.getServiceResult(RespCodeConstants.CommonCode.TRANS_SUC, true);

			}
			else
			{
				return ServiceResultFactory.getServiceResult(RespCodeConstants.CommonCode.DATA_STATE_ERROR, false);
			}
		}
		else
		{// 状态错误
			return ServiceResultFactory.getServiceResult(RespCodeConstants.CommonCode.DATA_STATE_ERROR, false);
		}
	}

	@Override
	public List<Drawing> getListByState(DrawingState state, String providerId)
	{
		List<Drawing> list = serviceFactory.getDaoFactory().getDrawingDao().getListByState(state, providerId);
		return list;
	}

	@Override
	public void updateState(List<Long> idList, DrawingState state)
	{
		for (Long id : idList)
		{
			serviceFactory.getDaoFactory().getDrawingDao().updateState(id, state);
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException
	{
		// TODO Auto-generated method stub
		this.context = context;
	}

}
